package com.config.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.*;

@Component
@Slf4j
public class CaptureResponseFilter implements GlobalFilter, Ordered {
    protected static final String HANDLER_MAPPER_HEADER = "X-Gateway-Handler-Mapper-Class";

    protected static final String ROUTE_ID_HEADER = "X-Gateway-RouteDefinition-Id";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // disable the infinite redirect uri
        URI uri = exchange.getAttributeOrDefault(GATEWAY_REQUEST_URL_ATTR,
                null);
        String path = uri.getPath();
        if (path.contains("httpbin/httpbin")) {
            return Mono
                    .error(new IllegalStateException("recursive call to /httpbin"));
        }

        log.info("intercepter the url : {}", uri);

        String value = exchange.getAttributeOrDefault(GATEWAY_HANDLER_MAPPER_ATTR,
                "N/A");
        if (!exchange.getResponse().isCommitted()) {
            exchange.getResponse().getHeaders().add(HANDLER_MAPPER_HEADER, value);
        }
        Route route = exchange.getAttributeOrDefault(GATEWAY_ROUTE_ATTR, null);
        if (route != null) {
            if (!exchange.getResponse().isCommitted()) {
                exchange.getResponse().getHeaders().add(ROUTE_ID_HEADER,
                        route.getId());
            }
        }


        HttpHeaders headers = exchange.getResponse().getHeaders();
        headers.entrySet().stream().forEach(kv -> {
            log.info("{}:{}", kv.getKey(), kv.getValue());
        });

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 10010;
    }
}
